package com.nip.irregularvebsdict.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nip.irregularvebsdict.R;
import com.nip.irregularvebsdict.adpters.IrregularVerbsAdapter;
import com.nip.irregularvebsdict.items.IrregularVerbDetailsItem;
import com.nip.irregularvebsdict.items.IrregularVerbItem;
import com.nip.irregularvebsdict.utilities.IrregularVerbsDetailsParser;
import com.nip.irregularvebsdict.utilities.IrregularVerbsParser;
import com.nip.irregularvebsdict.utilities.NetworkUtilities;
import com.nip.irregularvebsdict.utilities.assets.AssetsUtilities;
import com.nip.irregularvebsdict.utilities.constants.Constants;

public class VerbsFragment extends Fragment implements OnItemClickListener,
		TextWatcher {

	private ListView listView;
	private List<IrregularVerbItem> verbItems;
	private IrregularVerbsAdapter adapter;
	private Context context;
	public List<IrregularVerbItem> sources;
	private EditText txtSearch;
	private Bundle bundle;
	private AdView adView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View root = inflater.inflate(R.layout.fragment_list_vebs, container,
				false);
		initialize(root);
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		context = activity;
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {

		if (sources == null) {
			new IrregularVerbs().execute(AssetsUtilities.getInputStream(
					context, "garenal.xml"));
		}

		if (adView != null) {
			adView.resume();
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
		sources.clear();
		verbItems.clear();
		adapter.clear();
		sources = null;
		verbItems = null;
		adapter = null;
	}

	private void initialize(View view) {
		listView = (ListView) view.findViewById(R.id.lvIrregular);
		adView = (AdView) view.findViewById(R.id.adView);
		verbItems = new ArrayList<IrregularVerbItem>();
		adapter = new IrregularVerbsAdapter(context, 0, verbItems);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);

		txtSearch = (EditText) view.findViewById(R.id.txtSearch);
		txtSearch.addTextChangedListener(this);
		txtSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					if (adapter.getCount() > 0) {
						showDetails(0);
						// return true;
					}
				}
				return true;
			}
		});
		listView.setFocusable(true);
		listView.requestFocus();
		if (NetworkUtilities.isInternetAccess(context) && adView.getVisibility() == View.GONE) {
			adView.setVisibility(View.VISIBLE);
			adView.loadAd(new AdRequest.Builder()
					.addTestDevice("B04DDD10BB1F34C5737EC4C90B490AB9")
					.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
		}
	}

	private Intent intent;

	class IrregularVerbs extends
			AsyncTask<InputStream, Void, List<IrregularVerbItem>> {

		@Override
		protected List<IrregularVerbItem> doInBackground(InputStream... params) {
			if (params[0] == null) {
				return null;
			}
			return new IrregularVerbsParser(params[0]).getIrregularVerbItems();
		}

		@Override
		protected void onPostExecute(List<IrregularVerbItem> result) {
			AssetsUtilities.close();
			if (result == null) {
				return;
			}
			verbItems = result;
			sources = new ArrayList<IrregularVerbItem>(result);
			adapter.update(result);
			super.onPostExecute(result);
		}
	}

	private IrregularVerbDetailsItem item;

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		showDetails(arg2);
	}

	@Override
	public void afterTextChanged(Editable s) {
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		adapter.getFilter().filter(s);
	}

	void showDetails(int index) {
		item = new IrregularVerbsDetailsParser(AssetsUtilities.getInputStream(
				context, adapter.getItem(index).getBase() + ".xml"))
				.getIrregularVerbDetailsItem();
		AssetsUtilities.close();
		if (item == null) {
			showToast("data is updating...");
			return;
		}

		intent = new Intent(context, NIPVerbDetailsActivity.class);
		bundle = new Bundle();
		bundle.putSerializable(Constants.IRREGULAR_VERB_DETAILS_KEY, item);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private void showToast(String string) {
		Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
	}
}
